package com.example.casserver.controller;

import com.example.casserver.model.TicketGrantingTicket;
import com.example.casserver.service.TicketService;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/debug")
public class DebugController {

    private final TicketService ticketService;

    public DebugController(TicketService ticketService) {
        this.ticketService = ticketService;
    }
    
    @GetMapping("/cookies")
    public Map<String, String> debugCookies(HttpServletRequest request) {
        Map<String, String> cookieMap = new HashMap<>();
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie.getValue() + " (Path: " + cookie.getPath() + ")");
            }
        }
        return cookieMap;
    }

    @GetMapping("/tgt")
    public Map<String, Object> debugTgt(@CookieValue(name = "CASTGC", required = false) String tgtId) {
        Map<String, Object> result = new HashMap<>();
        result.put("tgtId", tgtId);
        
        if (tgtId != null) {
            TicketGrantingTicket tgt = ticketService.getTicketGrantingTicket(tgtId);
            if (tgt != null) {
                result.put("username", tgt.getUsername());
                result.put("valid", tgt.isValid());
                result.put("createdAt", tgt.getCreatedAt());
                result.put("expiresAt", tgt.getExpiresAt());
            } else {
                result.put("error", "TGT not found or invalid");
            }
        } else {
            result.put("error", "No TGT cookie found");
        }
        
        return result;
    }
} 